package ita.class1.group2.supermarket.common.jms;

import ita.class1.group2.supermarket.common.annotation.Autowired;
import ita.class1.group2.supermarket.common.annotation.Component;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.log4j.Logger;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;


@Component
public class JmsSender {

    private static final Logger LOGGER = Logger.getLogger(JmsSender.class);

    public static class Queue {
        public static final String LANCE_QUEUE = "tcp://10.222.29.157:61616/lance.queue";
    }

    @Autowired private JmsManager jmsManager;

    public void sendMessage(String queue, String msg) {

        String url = queue.substring(0, queue.lastIndexOf('/'));
        String queueName = queue.substring(url.length() + 1);

        Connection connection = jmsManager.getConnection(url);
        LOGGER.info("Create jms connection: " + url);

        Session session = null;
        MessageProducer messageProducer = null;

        if (connection != null) {
            try {
                session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
                LOGGER.info("Create jms session: " + queue);
            } catch (JMSException e) {
                LOGGER.error("Can not create jms session: " + queue + ", Message: " + e.toString());
            }
        }

        if (session != null) {
            try {
                messageProducer = session.createProducer(new ActiveMQQueue(queueName));
                LOGGER.info("Create jms message producer: " + queue);
            } catch (JMSException e) {
                LOGGER.error("Can not create jms message producer: " + queue + ", Message: " + e.toString());
            }
        }

        if (messageProducer != null) {
            try {
                messageProducer.send(session.createTextMessage(msg));
                session.commit();
                LOGGER.info("Send jms message to: " + queue + ", Message: " + msg);
            } catch (JMSException e) {
                LOGGER.info("Can not send jms message to: " + queue + ", Message: " + e.toString());
            }
        }

        jmsManager.close(messageProducer, session, connection);

    }

    /**
     * sor unit test
     * @param jmsManager
     */
    public void setJmsManager(JmsManager jmsManager) {
        this.jmsManager = jmsManager;
    }

}
